
module.exports = {
  /**
   * 获取参数类型, 返回：string, obejct, array...
   * @param {Any} value 
   */
  typeOf(value) {
    return Object.prototype.toString.call(value).slice(8, -1).toLowerCase();
  },
  /**
   * 深拷贝
   * 
   * @param {Any} data
   * @returns
   */
  deepClone(data) {
    var
      type = this.typeOf(data),
      obj;

    if (type === 'array') {
      obj = [];
      for (let i = 0, len = data.length; i < len; i++) {
        obj.push(this.deepClone(data[i]));
      }
      return obj;
    }

    if (type === 'object') {
      obj = {};
      for (let key in data) {
        obj[key] = this.deepClone(data[key]);
      }
      return obj;
    }
    return data;
  },
  /**
   * 是否是手机号码
   *
   * @param {String} value
   * @returns Boolean
   */
  isPhone(value) {
    var reg = /^((1[3-8][0-9])+\d{8})$/;
    return reg.test(value);
  },
  /**
   * 日期格式化
   *
   * @param {String} fmt
   * @param {Number} date
   * @returns
   */
  dateFormat(fmt, date) {
    if (!date || date === 'null') return "";
    date = Math.round(date * 1000)
    date = new Date(+date);
    fmt = fmt || "yyyy年MM月dd日";
    var o = {
      "y+": date.getFullYear(),
      "M+": date.getMonth() + 1, //月份
      "d+": date.getDate(), //日
      "h+": date.getHours(), //小时
      "m+": date.getMinutes(), //分
      "s+": date.getSeconds(), //秒
      "q+": Math.floor((date.getMonth() + 3) / 3), //季度
      "S+": date.getMilliseconds() //毫秒
    };
    for (var k in o) {
      if (new RegExp("(" + k + ")").test(fmt)) {
        if (k == "y+") {
          fmt = fmt.replace(RegExp.$1, ("" + o[k]).substr(4 - RegExp.$1.length));
        } else if (k == "S+") {
          var lens = RegExp.$1.length;
          lens = lens == 1 ? 3 : lens;
          fmt = fmt.replace(RegExp.$1, ("00" + o[k]).substr(("" + o[k]).length - 1, lens));
        } else {
          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
      }
    }
    return fmt;
  },
  // 节流函数
  throttle( fn, interval ) {
    let __self = fn; //被延时执行的函数
    let timer = null; //定时器
    let isFirstTime = true; //第一次调用

    return function() {
      let args = arguments;
      let __me = this;
      // 第一次执行
      if ( isFirstTime ) {
        __self.apply( __me, args );
        isFirstTime = false;
        // return isFirstTime = false;
      }
      // 如果上次的计时未结束，则本次不执行
      if ( timer ) {
        return false;
      }
      timer = setTimeout( function() {
        clearTimeout( timer );
        timer = null;
        isFirstTime = true;
        // __self.apply( __me, args );
      }, interval)
    }
  },
  /**
   * 序列化对象
   *
   * @param {Object} obj
   * @returns String
   */
  encodeURI( obj ) {
    obj = JSON.stringify( obj );
    obj = encodeURIComponent( obj );
    return obj;
  },
  /**
   * 反序列化
   *
   * @param {String} str
   * @returns Object
   */
  decodeURI( str ) {
    str = decodeURIComponent( str );
    str = JSON.parse( str );
    return str;
  },
  /**
   * 生成指定范围随机数
   *
   * @param {Number} Min 最小数
   * @param {Number} Max 最大数
   * @returns number
   */
  randomNum(Min, Max) {
    let range = Max - Min;
    var random = Math.random();
    var num = Min + Math.floor(random * (range + 1)); 
    return num;
  },
  /**
   * 生成有序数列
   *
   * @param {Number} len 数组长度
   * @param {Number} start 起始值
   * @returns
   */
  orderNums( len, start ) {
    let arr = [];
    for ( let i = 0; i < len; i ++ ) {
      arr[ i ] = i + start;
    }
    return arr;
  },
  /**
   * url参数解析为对象
   *
   * @param {String} query
   * @returns
   */
  queryParse( query ) {
    if ( !query ) {
      console.error( 'query is error: ' + query );
      return;
    }
    var params = {};
    var splits = query.split('?')[1] || query.split('?')[0];
    splits = splits.split('&');
    for ( var i = 0, len = splits.length; i < len; i ++ ) {
      var param = splits[ i ];
      param = param.split('=');
      params[ param[0] ] = param[ 1 ];
    }
    return params;
  },
  /**
   * 参数对象解析为url query字符串
   *
   * @param {Object} queryObj
   * @returns
   */
  querystring( queryObj ) {
    if ( !queryObj ) {
      console.error( 'query obj is error: ' + queryObj );
      return;
    }
    var queryStr = ''
    for (var key in queryObj) {
      if (queryObj.hasOwnProperty(key)) {
        var value = queryObj[key];
        queryStr += key + '=' + value + '&';
      }
    }
    queryStr = queryStr.slice(0, queryStr.length - 1);
    return queryStr;
  },
  /**
   * 删除对象属性，不修改原对象，返回删除后属性的新对象
   *
   * @param {Object} obj
   * @param {String} property
   * @returns
   */
  deleteProperty( obj, property ) {
    var o = {};
    for (var key in obj) {
      if (obj.hasOwnProperty(key) && key !== property) {           
        o[ key ] = obj[ key ];           
      }
    }
    return o;
  },
  /**
   * 毫秒格式化输出
   *
   * @param {Number} msec
   * @returns
   */
  msecFormat(msec) {
    let ms,
      second,
      seconds,
      minute;
    msec = Number( msec );
    ms = msec % 1000;
    seconds = Math.floor( msec / 1000 );
    ms = Math.floor( ms / 10 );
    ms = this.toDub( ms );
    second = this.toDub( seconds % 60 );
    minute = this.toDub( Math.floor( seconds / 60 ) );
    return {
      minute: minute,
      second: second,
      ms: ms
    }
  },
  /**
   * 洗牌算法生成乱序数组
   *
   * @param {Array} array
   * @param {Number} size 乱序的个数，从0开始
   * @returns
   */
  shuffle(array, size) {
    var index = -1,
      length = array.length,
      lastIndex = length - 1;
  
    size = size === undefined ? length : size;
    while (++index < size) {
      var rand = this.randomNum(index, lastIndex),
        value = array[rand];
  
      array[rand] = array[index];
      array[index] = value;
    }
    array.length = size;
    return array;
  },
  toDub( n ){
    return n < 10 ? "0" + n : "" + n;
  },
  /**
   * 小程序 新增列表数据，只setData新增数据
   *
   * @param {String} name 数组名称
   * @param {*} arr 新增数组
   * @param {*} start 已有数组长度，即setData起始位置
   */
  insertData( name, arr, start ) {
    let insertData = arr.reduce( ( data, item, index ) => {
      let i = start + index;
      let key = name + '[' + i + ']';
      data[ key ] = item;
      return data;
    }, {} )
    return insertData;
  },
  getProData( arrName, index, proName, data ) {
    let 
      obj = {},
      pro
    if (proName) {
      pro = arrName + '[' + index + ']' + '[' + proName + ']';
    } else {
      pro = arrName + '[' + index + ']';
    }
    obj[pro] = data;
    return obj;
  }
}